import subprocess


def release_and_renew_ip_windows():
    try:
        # 释放当前 IP 配置
        result = subprocess.run(["ipconfig", "/release"], capture_output=True, text=True)
        if result.returncode != 0:
            print(f"释放 IP 失败: {result.stderr}")
        else:
            print("已成功释放 IP 地址")
        #   控制台显示result 并且根据\n进行换行
            print("新的 IP 地址:")
            for line in result.stdout.split("\n"):
                print(line)


        # 重新获取 IP 配置
        result = subprocess.run(["ipconfig", "/renew"], capture_output=True, text=True)
        if result.returncode != 0:
            print(f"获取 IP 失败: {result.stderr}")
        else:
            print("已成功重新获取 IP 地址")
            print("新的 IP 地址:")
            for line in result.stdout.split("\n"):
                print(line)

    except subprocess.CalledProcessError as e:
        print(f"执行命令时出错: {e}")
    except Exception as e:
        print(f"发生未知错误: {e}")


# 执行函数
release_and_renew_ip_windows()